import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import '../models/task.dart';
import '../models/member.dart';
import '../providers/member_provider.dart';
import '../services/database_service.dart';
import 'package:provider/provider.dart';
import '../services/notification_service.dart';
import '../providers/auth_provider.dart';

class TaskProvider with ChangeNotifier {
  final DatabaseService _db = DatabaseService();
  final NotificationService _notifications = NotificationService();
  List<Task> _tasks = [];
  bool _isLoading = false;

  List<Task> get tasks => _tasks;
  List<Task> get completedTasks => _tasks.where((task) => task.isCompleted).toList();
  List<Task> get pendingTasks => _tasks.where((task) => !task.isCompleted).toList();
  bool get isLoading => _isLoading;

  Future<void> loadTasks() async {
    _isLoading = true;
    notifyListeners();

    try {
      _tasks = await _db.getAllTasks();
    } catch (e) {
      print('Error loading tasks: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> addTask(String title, String description, {
    DateTime? dueDate,
    Color? color,
    TaskPriority priority = TaskPriority.medium,
    String? assignedTo,
  }) async {
    try {
      final task = Task(
        id: const Uuid().v4(),
        title: title,
        description: description,
        createdAt: DateTime.now(),
        dueDate: dueDate,
        color: color ?? Colors.blue,
        priority: priority,
        assignedTo: assignedTo,
      );

      await _db.insertTask(task);
      if (dueDate != null) {
        await _notifications.scheduleTaskReminder(task);
      }
      await loadTasks();
    } catch (e) {
      print('Error adding task: $e');
      rethrow;
    }
  }

  Future<void> updateTask(Task task) async {
    try {
      await _db.updateTask(task);
      await _notifications.cancelTaskReminder(task);
      if (task.dueDate != null && !task.isCompleted) {
        await _notifications.scheduleTaskReminder(task);
      }
      await loadTasks();
    } catch (e) {
      print('Error updating task: $e');
      rethrow;
    }
  }

  Future<void> deleteTask(String id) async {
    try {
      final task = _tasks.firstWhere((t) => t.id == id);
      await _notifications.cancelTaskReminder(task);
      await _db.deleteTask(id);
      await loadTasks();
    } catch (e) {
      print('Error deleting task: $e');
      rethrow;
    }
  }

  Future<void> toggleTaskCompletion(Task task) async {
    try {
      final updatedTask = task.copyWith(isCompleted: !task.isCompleted);
      await _db.updateTask(updatedTask);
      if (updatedTask.isCompleted) {
        await _notifications.cancelTaskReminder(task);
      } else if (updatedTask.dueDate != null) {
        await _notifications.scheduleTaskReminder(updatedTask);
      }
      await loadTasks();
    } catch (e) {
      print('Error toggling task completion: $e');
      rethrow;
    }
  }

  Future<void> moveTask(String taskId, int newIndex) async {
    try {
      // 实现任务重新排序的逻辑
      // 这需要在数据库中添加一个 order 字段
      // 暂时以不实现
    } catch (e) {
      print('Error moving task: $e');
      rethrow;
    }
  }

  Future<void> reorderTask(String taskId, int newPosition) async {
    try {
      // 获取要移动的任务
      final task = _tasks.firstWhere((t) => t.id == taskId);
      
      // 更新数据库中的任务位置
      await _db.reorderTasks(taskId, newPosition);
      
      // 重新加载任务以获取正确的顺序
      await loadTasks();
      
      notifyListeners();
    } catch (e) {
      print('Error reordering task: $e');
    }
  }

  // 获取所有任务中的唯一���员列表
  List<Member> getUniqueMembers(BuildContext context) {
    final memberProvider = Provider.of<MemberProvider>(context, listen: false);
    
    final memberIds = _tasks
        .where((task) => task.assignedTo != null)
        .map((task) => task.assignedTo!)
        .toSet()
        .toList();

    final members = memberIds
        .map((id) => memberProvider.getMemberById(id))
        .where((member) => member != null)
        .cast<Member>()
        .toList();
    
    members.sort((a, b) => a.name.compareTo(b.name));
    return members;
  }

  // 按成员筛选任务
  List<Task> getTasksByMember(String memberId) {
    return _tasks.where((task) => task.assignedTo == memberId).toList();
  }

  // 添加权限检查方法
  bool canEditTask(BuildContext context, Task task) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.currentUser;
    
    if (currentUser == null || currentUser.role == MemberRole.guest) return false;  // 访客无权编辑
    if (currentUser.role == MemberRole.admin) return true;  // 管理员可以编辑所有任务
    return task.assignedTo == currentUser.id;  // 普通成员只能编辑分配给自己的任务
  }

  bool canDeleteTask(BuildContext context, Task task) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.currentUser;
    
    return currentUser?.role == MemberRole.admin;  // 只有管理员可以删除任务
  }

  bool canCreateTask(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.currentUser;
    
    return currentUser != null && currentUser.role != MemberRole.guest;  // 访客不能创建任务
  }

  bool canAssignTask(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.currentUser;
    
    return currentUser?.role == MemberRole.admin;  // 只有管理员可以分配任务
  }

  bool canCompleteTask(BuildContext context, Task task) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.currentUser;
    
    if (currentUser == null || currentUser.role == MemberRole.guest) return false;  // 访客不能标记完成
    if (currentUser.role == MemberRole.admin) return true;  // 管理员可以标记所有任务
    return task.assignedTo == currentUser.id;  // 普通成员只能标记分配给自己的任务
  }
} 